/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.dusa.switco;

/**
 *
 * @author vdusa
 */
public class QuadraticCostFunction  extends ConvexCostFunction {
    public double a = 0;
    public double b = 0;
    public double c = 0;

    public QuadraticCostFunction(double a, double b, double c){
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public Double evaluate(double t) throws EvaluationException {
        return a*((t+getTimeShift())*(t+getTimeShift())) + b*(t+getTimeShift()) + c;
    }

    void add(QuadraticCostFunction quadraticCostFunction) {
        //according to the time shift 's' we must calculate a,b,c correctly:
        //a(x+s)^2 + b(x+s)+c = ax^2 + (2as+b)x + (as^2+bs+c)
        double s = quadraticCostFunction.getTimeShift();
        this.a += quadraticCostFunction.a;
        this.b += 2*quadraticCostFunction.a*s+quadraticCostFunction.b;
        this.c += quadraticCostFunction.a*s*s + quadraticCostFunction.b*s+quadraticCostFunction.c;
    }

    public Double getArgMin(){
        if(a>0){
            GlobalSettings globalSettings = GlobalSettings.getInstance();
            double result = (-b)/(2*a);
            if (result < globalSettings.getMinT()) result=globalSettings.getMinT();
            if (result > globalSettings.getMaxT()) result=globalSettings.getMaxT();
            return globalSettings.roundToPrecisionLimit(result);
        } else{
            return Double.NEGATIVE_INFINITY;
        }
    }
}
